package com.rtx.express.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;
import com.vip.osp.sdk.context.InvocationContext;

import vipapis.jitx.GetOrderLabelRequest;
import vipapis.jitx.GetTransportNosRequest;
import vipapis.jitx.JitXServiceHelper.JitXServiceClient;
import vipapis.jitx.OrderLabel;
import vipapis.jitx.PrintDetail;

@RtxExpressApi(expressApiName = "唯品会-JITX")
@Service("快递接口WP")
public class WPExpressAPI  implements IExpressService {

	Logger log = LoggerFactory.getLogger(this.getClass());

	private static String appKey ="67c99bb9";
	private static String appSecret ="CD4F571AAB661D6C09A6B567B566AFD0";
	private static String appURL ="https://gw.vipapis.com/";
	private static String language ="zh";
	
	//三利
//	供应商ID 8034 
//	供应商编码 115110
//	{
//	    "access_token": "1D31ECC08A6C0DA4871983E60D085BDFE7216E25",
//	    "refresh_expires_time": 1723256934000,
//	    "refresh_token": "FFBF997AE67B4CABD492DA0AA892D7A35A2DA2B6",
//	    "open_id": "15185479796C873639CDAB6B7FD0C638",
//	    "open_id": "15185479796C873639CDAB6B7FD0C638", 
//	    "expires_in": 7775999
//	}
//暇步士	
//	{
//	    "access_token": "F8CC0FAF484B27057203BDABE40AEC1903421B21",
//	    "refresh_expires_time": 1724232729000,
//	    "refresh_token": "82ADC8B43A33AA637F8A1BA6B7093BDC9424DFD5",
//	    "open_id": "127795620A50BE9939CDAB6B7FD0C638",
//	    "expires_in": 7775999
//	}


	private JitXServiceClient initVOPClient(String accesstoken) {
		JitXServiceClient client=new JitXServiceClient();
		InvocationContext invocationContext=InvocationContext.Factory.getInstance();
		invocationContext.setAppKey(appKey);
		invocationContext.setAppSecret(appSecret);
		invocationContext.setAppURL(appURL);
		invocationContext.setLanguage(language);
		invocationContext.setAccessToken(accesstoken);
		return client;
	}

	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		StringBuffer sb = new StringBuffer();
		try {
			String accessToken = config.getAccessToken();

			JitXServiceClient client= initVOPClient (accessToken);

			GetTransportNosRequest getTransportNosRequest = mappingTransportNosRequest(bo);

			log.info("订单-{}-唯品会TransportNo请求：{}", task.getExternorderkey(), JSON.toJSON(getTransportNosRequest));
			sb.append("请求"+JSON.toJSON(getTransportNosRequest));
			List<String> transportNoList = client.getTransportNos(getTransportNosRequest);
			sb.append("响应"+JSON.toJSON(transportNoList));
			log.info("订单-{}-唯品会TransportNo返回：{}", task.getExternorderkey(), transportNoList);

			if (null !=transportNoList && transportNoList.size() >0) {
				bo.setCallCreateOrderAPIData(JSON.toJSONString(transportNoList));
				bo.setCallCreateOrderAPIResult("ok");

				//获取打印报文
				getPrintTemplate(bo,sb);

				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				result.setExternorderkey(task.getExternorderkey());
				result.setWaybillNo(transportNoList.get(0));
				result.setPrintData("   ");
				bo.setExpressResult(result);

			}else {
				bo.setCallCreateOrderAPIData(JSON.toJSONString(transportNoList));
				bo.setMsg(bo.getMsg());
				throw new RuntimeException(JSON.toJSONString(transportNoList)+sb.toString());
			} 

		} catch (Exception e) {
			bo.setCallCreateOrderAPIData(e.getMessage());
			bo.setMsg(bo.getMsg());
			log.info("订单-{}-请求唯品会接口失败：{}", task.getExternorderkey(), e);
			throw new RuntimeException(e.getMessage());
		}

	}

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub

	}


	/**
	 * 在线文档
	 * https://vop.vip.com/home#/api/method/detail/vipapis.jitx.JitXService-1.0.0/getTransportNos
	 * getTransportNos
	 * 获取运单号服务
	 * @param bo
	 * @return
	 */
	private GetTransportNosRequest mappingTransportNosRequest(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();

		GetTransportNosRequest request = new GetTransportNosRequest();
		request.setVendor_id(Integer.parseInt(config.getVendorId()));
		request.setOrder_sn(task.getTid());
		request.setCarrier_code(config.getPlatformCarriercode());

		return request;
	}

	
	/**
	 * @param bo
	 * @param accesstoken
	 * @throws Exception 
	 */
	public void getPrintTemplate(ExpressBO bo,StringBuffer sb) throws Exception {
		PlExpressApi task = bo.getExpressTask();

		//映射报文
		List<OrderLabel> response = callPrintTemplate(bo,sb);

		if(response != null && response.size() > 0) {
			bo.setCallCreateOrderAPIData(JSON.toJSONString(response));
			bo.setCallCreateOrderAPIResult("ok");
			
			OrderLabel orderLabel = response.get(0);
			PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
			result.setJitxboxNo(orderLabel.getBox_no()+"");
			result.setJitxcarrierCode(bo.getExpressConfig().getPlatformCarriercode());
			result.setJitxLogisticsCode("JITX"+bo.getExpressConfig().getPlatformCarriercode());
			result.setJitxorderSn(task.getTid());
			String label = response.get(0).getOrder_label();
			if(label.startsWith("[")&&label.endsWith("]")) {
				List<JSONObject> order_labelList = JSON.parseArray(response.get(0).getOrder_label(),JSONObject.class);
				Map<String,String> orderLabelMap = new HashMap<>();
				for(JSONObject order_label:order_labelList) {
					orderLabelMap.put(order_label.getString("fieldCode"), order_label.getString("fieldValue"));
				}
				result.setJitxpickCode(orderLabelMap.get("pickCode"));
				result.setJitxproCode(orderLabelMap.get("proCode"));
				result.setJitxthirdCustName(orderLabelMap.get("thirdCustName"));
				result.setJitxtotalPackage(orderLabelMap.get("totalPackage"));
				result.setJitxtransportNo(orderLabelMap.get("transportNo"));
				
				
			}else {
				result.setPrintData(label);
			}
			
			result.setExternorderkey(task.getExternorderkey());
			result.setWaybillNo(task.getExpresscode());

		}
	}

	/**
	   *  在线文档
	 * https://vop.vip.com/home#/api/method/detail/vipapis.jitx.JitXService-1.0.0/getPrintTemplate
	 * getPrintTemplate
	 * @param bo
	 * @return
	 */
	private List<OrderLabel> callPrintTemplate(ExpressBO bo,StringBuffer sb) throws Exception {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		
		JitXServiceClient client = new JitXServiceClient();
		InvocationContext invocationContext=InvocationContext.Factory.getInstance();
		invocationContext.setAppKey(appKey);
		invocationContext.setAppSecret(appSecret);
		invocationContext.setAppURL(appURL);
		invocationContext.setLanguage(language);
		invocationContext.setAccessToken(config.getAccessToken());
		GetOrderLabelRequest request = new GetOrderLabelRequest();
		request.setVendor_id(Integer.parseInt(config.getVendorId()));
		ArrayList<PrintDetail> print_details = new ArrayList<PrintDetail>();
		PrintDetail value = new PrintDetail();
		value.setOrder_sn(task.getTid());
		value.setTransport_no(task.getExpresscode());
		value.setBox_no(1);
		value.setCarrier_code(config.getPlatformCarriercode());
		value.setTotal_package(1);
		ArrayList<String> goods_info = new ArrayList<String>();
		goods_info.add("");
		value.setGoods_info(goods_info);
		value.setDelivery_warehouse_code("");
		print_details.add(value);
		request.setPrint_details(print_details);
		request.setTemplate_type("");
		sb.append("模板请求"+JSON.toJSON(request));
		log.info("订单-{}-唯品会PrintTemplate请求：{}", task.getExternorderkey(), JSON.toJSON(request));
		List<OrderLabel> orderLabelList = client.getPrintTemplate(request);
		log.info("订单-{}-唯品会PrintTemplate返回：{}", task.getExternorderkey(), JSON.toJSON(orderLabelList));
		sb.append("模板响应"+JSON.toJSON(orderLabelList));
		return orderLabelList;
	}
	
}
